package com.googlecode.bipol.war.services;

import java.io.Serializable;
import java.util.List;

import com.googlecode.bip.dao.DAOFactory;
import com.googlecode.bip.entity.IQuestion;
import com.googlecode.bip.entity.ITopic;
import com.googlecode.bip.entity.Question;

/**
 * 
 *
 */
public class QuestionManagerImpl implements QuestionManager, Serializable {
    // Seem to must implement java.io.Serializable 
    private static final long serialVersionUID = 1L;
 
    
    @Override
    public IQuestion createQuestion(int topicId, String name,
            String description, String idLocal, int minValue, int maxValue,
            int defaultValue) throws ServiceException {

        // Check that topic exists
        ServicesHelper.getExistingTopic(topicId, idLocal);
        // Create the question based on given parameters
        Question q = new Question();
        q.setParentIdTopic(topicId);
        q.setName(name);
        q.setDescription(description);
        q.setMinValue(minValue);
        q.setMaxValue(maxValue);
        q.setDefaultValue(defaultValue);
        q.setIdLocal(idLocal);
        // Insert the new question
        try {
            if (DAOFactory.getDAOFactory().getQuestionDAO().insertQuestion(q)) {
                return q;
            } else {
                throw new ServiceException("Error when saving question: Unknown reason (please contact the administrator)");
            }
        } catch(Exception e) {
            throw new ServiceException("Error when saving question: "+e.getMessage());
        }
    }
    
    @Override
    public IQuestion removeQuestion(int idquestion, String idlocal) throws ServiceException {
    	// Check that question exists
    	IQuestion q = ServicesHelper.getExistingQuestion(idquestion, idlocal);
    	// Delete topic
    	try {
    		//FIXME Implement (DAOFactory.getDAOFactory().getQuestionDAO().deleteQuestionLocal()
    		if (DAOFactory.getDAOFactory().getQuestionDAO().deleteQuestion(q.getIdQuestion())) {
                return q;
            } else {
                throw new ServiceException("Error when deleting question: Unknown reason (please contact the administrator)");
            }
        } catch(Exception e) {
            throw new ServiceException("Error when deleting question: "+e.getMessage());
        }
    }
    
    public List<IQuestion> getQuestionsOfTopic(int idtopic, String idlocal) throws ServiceException {
    	// Check that topic exists
    	ServicesHelper.getExistingTopic(idtopic, idlocal);
    	// Get related questions
    	try {
            return DAOFactory.getDAOFactory().getQuestionDAO().findQuestions(idtopic,idlocal);
        } catch(Exception e) {
            throw new ServiceException("Error when getting questions of topic with id \'"+idtopic+"\' and local \'"+idlocal+"\': "+e.getMessage());
        }
    }

}
